

#include <rtthread.h>
#include <touch_800x480.h>
#include <drv_gpio.h>

#define DBG_TAG         "touch"
#define DBG_LVL         DBG_LOG
#include <rtdbg.h>

#define TOUCH_THREAD_STACK_SIZE         1024
#define TOUCH_THREAD_PRIORITY           19

#define TOUCH_IRQ_PIN                   GET_PIN(I, 11)

static rt_sem_t touch_sem;

static void irq_cb(void *arg)
{
    rt_sem_release(touch_sem);
}

static void touch_thread_entry(void *para)
{
    touch_sem = rt_sem_create("touch_sem", 0, RT_IPC_FLAG_FIFO);
    
    rt_pin_attach_irq(TOUCH_IRQ_PIN, PIN_IRQ_MODE_FALLING, irq_cb, RT_NULL);
    rt_pin_irq_enable(TOUCH_IRQ_PIN, RT_TRUE);
    
    while(1)
    {
        rt_sem_take(touch_sem, RT_WAITING_FOREVER);
        Touch_Scan();
    }
}

static int touch_init(void)
{
    uint8_t ret = ERROR;
    rt_thread_t tid;
    ret = Touch_Init();
    if(ret != SUCCESS)
    {
        LOG_W("touch init error");
        return -RT_ERROR;
    }
    
    tid = rt_thread_create("touch_scan", touch_thread_entry, RT_NULL,
                            TOUCH_THREAD_STACK_SIZE, TOUCH_THREAD_PRIORITY, 20);
    RT_ASSERT(tid != RT_NULL);
    rt_thread_startup(tid);
    
    return RT_EOK;
}
INIT_APP_EXPORT(touch_init);
